<template>
    <div>

      <div>接口地址 url</div>
      <div>
        <ol>
          <li>  <el-checkbox v-model="iscwbw">是否财务报文</el-checkbox> </li>
          <li>上传文件xml:

            <input type="file" ref="upload" accept=".xml" @change="executorListchange" id="file_executor" class="outputlist_upload"></li>

        </ol>




      </div>
      <div>需要修改的key {{fileString}}

          <div style="border:1px  ">值：
            <el-button type="primary"  size="mini" @click="addNewTask(tasks)">新增</el-button>

            <el-table :data="tasks">
              <el-table-column label="key">
                <template slot-scope="{row,index}">
                  <span v-show="!row.editable" @dblclick="edit(row,index)">{{row.key }}</span>
                  <el-input  v-show="row.editable" v-model="row.key"></el-input>
                </template>
              </el-table-column>


              <el-table-column
                type="index"
                width="50">

                <template slot-scope="{row,$index}">
                  <span v-show="!row.editable">{{$index+1}}</span>
                  <el-button v-show="row.editable" type="primary" icon="el-icon-check" size='mini'
                             @click=updatetask(row)></el-button>
                  <el-button class="marginleftset" v-show="row.editable" type="primary" icon="el-icon-close" size='mini'
                             @click=deletetask($index,row)></el-button>

                </template>
              </el-table-column>
              <el-table-column label="value">
                <template slot-scope="{row,index}">
                  <span v-show="!row.editable" @dblclick="edit(row,index)">{{row.value }}</span>
                  <el-input  v-show="row.editable" v-model="row.value"></el-input>
                  <!-- <span v-show="!row.editable" @dblclick="edit(row,index)">{{row.executor}}</span>
                   <el-input v-show="row.editable"  v-model="row.executor.toString()"  ></el-input>-->

                </template>
              </el-table-column>

              <el-table-column label="confirm">
                <template slot-scope="{row,index}">
                  <!-- <span v-show="!row.editable" @dblclick="edit(row,index)">{{row.executor}}</span>
                   <el-input v-show="row.editable"  v-model="row.executor.toString()"  ></el-input>-->
                  <el-button type="primary" size="mini" @click="edit(row,index)" v-show="!row.editable">修改</el-button>
                  <el-button type="primary" size="mini" @click="updateValue(row,index)" v-show="row.editable">确定</el-button>
                </template>
              </el-table-column>

            </el-table>



      </div>

        </div>
      <div>
        <el-input placeholder="请输入内容" v-model="express"  clearable ></el-input>
        {{keys}}
        <button @click="getkey">获取当前节点的key</button></div>
      <div><el-button  @click="downLoadFile"  icon="el-icon-download" type="primary">生成xml</el-button></div>

    </div>
</template>

<script>
 // import readxml from 'xmlreader'
  // var readxml = require('xmlreader')
  import Xml2js from 'xml2js'
  import $ from 'jquery'
 import  vue from 'vue'
 import jsonpath from 'advanced-json-path'
// import zip from 'compressing'  //这个包开启后 前端会报错， 估计包有问题

    export default {
        name: "xmlParse",
      data(){
        return {
          fileString:"121212",
          xmlObject: {},
          filename:'',
          subxmlObject:{},
          tasks:[],
          express:'',
          keys:[],
          iscwbw:false,
          cjbdxmlExpression:'$.taxML.SB100VO.SB100BdxxVO.cjbdxml',//写死
          cjbdxmlExpressionNoJsonPath : 'taxML.SB100VO.SB100BdxxVO.cjbdxml'
        };
      },
      methods:{
        executorListchange(){
          this.readXml()
          this.tasks = []


        },
        readXml(){
          let xmlParser = new Xml2js.Parser({explicitArray: false, ignoreAttrs: false});

          let that = this
          var files = $('#file_executor').prop('files')

          if (null == files[0]) return;

          console.log('输出file属性')
          console.log(files[0])

          this.filename = files[0].name
          var promise = new Promise(((resolve, reject) => {
            var reader = new FileReader();//新建一个FileReader
            reader.readAsText(files[0], "UTF-8");//读取文件
            reader.onload = function(evt) { //读取完文件之后会回来这里
              this.fileString = evt.target.result; // 读取文件内容
              xmlParser.parseString(this.fileString,function (err,rep) {
                if (null!= err){console.log(err);return}
                resolve(rep)
              })
            }
          }))
          promise.then(value =>{
            console.log(value)
            this.xmlObject = value

            //this.fileString = this.xmlObject.taxML.ywbw.A100000.zbForm.yysr

          //  console.log(jsonpath(value,'$.taxML.ywbw.A100000.zbForm.yysr'))
          }).then(()=>{
            let needXmlbw =''
            if(this.iscwbw){
              needXmlbw = jsonpath(this.xmlObject,this.cjbdxmlExpression)
              //  console.log(needXmlbw)
              new Promise((resolve, reject) => {
                let xmlParser = new Xml2js.Parser({explicitArray: false, ignoreAttrs: false});
              //  console.log(needXmlbw)
                xmlParser.parseString(needXmlbw,function (err,rep) {
                  if (null!= err) {
                  that.warn('请确认报文类型，再重新上传文件')
                   // warn()
                    console.log(err);return}
                  resolve(rep)
                })

              }).then(value => {

              //  console.log(value)
                this.subxmlObject = value ;  console.log(JSON.stringify(this.subxmlObject))
              })

            }

          })

        },

        downLoadFile(){
         if (JSON.stringify(this.xmlObject) == '{}') return;
          let xmlBuild = new Xml2js.Builder();
          let subxml;
          if (this.iscwbw){
            subxml =  xmlBuild.buildObject(this.subxmlObject)
            this.setValue(this.cjbdxmlExpressionNoJsonPath,this.xmlObject,subxml)
          }

          let xml = xmlBuild.buildObject(this.xmlObject);
          console.log(xml)

          console.log("downloadfile")
          let content = xml
          let fileName= this.filename
          let aTag = document.createElement('a');
          let blob = new Blob([content]);　　// 这个content是下载的文件内容，自己修改
          aTag.download = fileName;　　　　　　// 下载的文件名
         aTag.href = URL.createObjectURL(blob)

          aTag.click();
        URL.revokeObjectURL(blob)

        },

        getkey(){
          console.log('====')
         let extmp = this.keyCalibration(this.express,this.iscwbw ?this.subxmlObject : this.xmlObject)
          extmp = '$.'+extmp
          console.log(extmp)
          console.log(JSON.stringify(jsonpath(this.iscwbw ?this.subxmlObject : this.xmlObject,extmp)))


     //   console.log(this.keys)
        },

        updateValue(row,index){  //获取对应的key值  ，如表达式出错 则异常提示
          vue.delete(row,'editable')
          this.setValue(row.key, this.iscwbw ?this.subxmlObject : this.xmlObject,row.value)
          console.log(JSON.stringify(this.iscwbw ?this.subxmlObject : this.xmlObject))
        },


        addNewTask(tasks){
          let newtask={

            key:'',
            value:'',
            editable:true
          }
          tasks.push(newtask)
        },

        edit(value2, index) {
          vue.set(value2, 'editable', true)
        },

        deletetask(index,row){

            this.tasks.splice(index,1)
           // return

         // vue.delete(row,'editable')

        },
        updatetask(row) {
         // if(row.name != '' && row.name )

         // this.row.key =  this.keyCalibration(row.key.trim(),this.xmlObject)
         vue.set(row,'key',this.keyCalibration(row.key.trim(),this.iscwbw ?this.subxmlObject : this.xmlObject))
          vue.delete(row, 'editable')

          vue.set(row,'value',this.findValue(row.key.trim(),this.iscwbw ?this.subxmlObject : this.xmlObject))


          
        },

        findValue (expression,obj) {

          let arr = expression.replace(/\"/g,'').split(',')
          let j =obj

          if (arr.length > 1){// 'xml.key.value,"aa","a","bb'


            let searchkey = arr[1]
            let searchValue = arr[2]
            let changekey = arr[3]
            let subarr = arr[0].split('.');
            let isFindSearchValue = false;
            for (let i in subarr){
              j=j[subarr[i]]
            }
            console.log(j )


            for (let i in j){
              if (j[i][searchkey] == searchValue){

                j= j[i][changekey]
                isFindSearchValue = true
                break
              }
            }

            if (!isFindSearchValue){
              this.warn(`未发现值为${searchValue}的键${searchkey}`)
              return
            }

          } else {    // xml.key.value2

            let subarr =   expression.split('.')

            for (let i in subarr){

              j=j[subarr[i]]
            }


          }

          return j
        },


        setValue(expression,obj,updatevalue) {

          let arr = expression.replace(/\"/g,'').split(',')
          let j =obj

          if (arr.length > 1){              // 'xml.key.value,"aa","a","bb'
            let subarr = arr[0].split('.')

            for (let i in subarr){
              j=j[subarr[i]]
            }

            for (let i in j){
              let key = arr[1]
              let searchValue = arr[2]
              let changekey = arr[3]

              if (j[i][key] == searchValue){

                j[i][changekey] = updatevalue
                return
              }
            }

          } else {    // xml.key.value2

            let subarr =   expression.split('.')

            for (let i in subarr){
              console.log(updatevalue)
                console.log(i)
              if (i== subarr.length-1){
                console.log('============')
                j[subarr[i]]=updatevalue
                  return
              }
              j=j[subarr[i]]
            }

          }

        },

       keyCalibration  (expression,obj) {  //根据  json中大小写 来校准  expression 中的key值

          let startStr = 'taxML' 

         console.log('keyCalibration contains')


        // console.log(!expression.toLowerCase().startsWith(startStr.toLowerCase()))
         if (!expression.toLowerCase().startsWith(startStr.toLowerCase())) {
             expression = 'taxML.'+expression
            console.log('expression:'+expression)
         }




          let arr = expression.replace(/\"/g,'').split(',')
          let subarr = arr[0].split('.')
          let objtmp = obj
          let isFindKey = true

          for (let i in subarr){   //校准subarr
            if (!isFindKey && i>0){
              //执行 没有发现key  未发现
              this.warn('找不到对应键值：'+subarr[i-1])
              return
            }
            let keys = this.getObjkey(objtmp)
            for(let j in keys){


              if (keys[j].toLowerCase() == subarr[i].toLowerCase()){
                subarr[i]=keys[j]
                objtmp = objtmp[keys[j]]
                isFindKey = true
                break
              }


            }


          }

         if (!isFindKey ){
           //执行 没有发现key  未发现
           this.warn('找不到对应键值：'+subarr[i-1])
           return
         }


          if (arr.length >1){
            //校准 二维数据
            let flag =0

            let keys = this.getObjkey(objtmp[0])
            for (let j in keys){
              if (keys[j].toLowerCase() == arr[1]){
                arr[1] = keys[j]
                flag++

              }
              if (keys[j].toLowerCase() == arr[3]){
                arr[3] = keys[j]
                flag++
              }

              if (flag == 2 ){
                break
              }

            }



            if (flag <2 ){
              //执行 没有发现key  未发现
              this.warn('找不到对应键值：'+arr[1] +'或' + arr[3])

              return
            }
          }


          //重新组装
          let newEXpre = ''
          for (let index in subarr){
            if (subarr.length -1 == index) {
              newEXpre = newEXpre + subarr[index]
            }else{
              newEXpre = newEXpre + subarr[index]+'.'
            }


          }
          for(let i =1 ; i<arr.length ;i++){
            newEXpre = newEXpre +','+ arr[i]
          }



          return newEXpre

        },

        getObjkey (obj) {
          let arr=[]
          for (let i in obj){
            arr.push(i)
          }

          return arr
        },


        warn(message) {
          this.$alert(message, '标题名称', {
            confirmButtonText: '确定',
            callback: action => {
              this.$message({
                type: 'info',
                message: `action: ${ action }`
              });
            }
          });
        }




      },
      computed:{

      }

    }
</script>

<style scoped>

</style>
